<?php

use Core\AdminController;
use Models\Category;

class CategoryController extends AdminController
{
	public function __construct()
	{
		parent::__construct();

		$this->lang->load('admin_category', $this->session->admin_language);
	}

	public function index()
	{
		$categories = Category::order_by('sort desc,id desc')->get();
		$this->load->view('admin/category/index', [
			'categories' => $categories,
		]);
	}

	public function create()
	{
		$this->load->library('form_validation');
		$this->form_validation->set_rules('title', '标题', 'required|max_length[32]')
		->set_rules('en_title', '英文标题', 'required|max_length[32]')
		->set_rules('image', 'icon名称', 'trim')
		->set_rules('parent_id', '父分类', 'integer')
		->set_rules('sort', '排序', 'integer')
		->set_rules('ad', '分类广告', 'trim');
		if ($this->form_validation->run()) {
			$category = new Category();
			$category->load($this->input->post());
			$category->add();

			return $this->success();
		}

		$parent_categories = Category::where('parent_id', 0)->get();
		$this->load->view('admin/category/create', [
			'parent_categories' => $parent_categories
		]);
	}

	public function edit($id)
	{
		$category = new Category();

		if (!$category->find($id)) {
			show_404();
		}

		$this->load->library('form_validation');
		$this->form_validation->set_rules('title', '标题', 'required|max_length[32]')
		->set_rules('en_title', '英文标题', 'required|max_length[32]')
		->set_rules('image', '图片', 'trim')
		->set_rules('parent_id', '父分类', 'integer')
		->set_rules('sort', '排序', 'integer')
		->set_rules('ad', '分类广告', 'trim');
		if ($this->form_validation->run()) {
			$category->load($this->input->post());
			$category->update();

			return $this->success();
		}

		$parent_categories = Category::where('parent_id', 0)->get();
		$this->load->view('admin/category/create', [
			'parent_categories' => $parent_categories,
			'category' => $category,
		]);
	}

	public function delete($id)
	{
		$category = new Category();

		if (!$category->find($id)) {
			show_404();
		}

		$category->delete();

		return $this->response(['error' => 'success']);
	}

	/**
	 * 获取二级类别
	 */
	public function get_categorys($category_id){
		$category = new Category;
		$data['categorys'] = $category->where('parent_id',$category_id)->order_by('sort','desc')->get();

		return $this->response([
			'code'=>0,
			'data'=>$data['categorys']
		]);
	}
}